package com.wuyou.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuyou.entity.User;
import com.wuyou.exception.LoginException;
import com.wuyou.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class LoginRealm extends AuthorizingRealm {


    @Autowired
    private IUserService userService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //实体类
//        SysPerson person = (SysPerson) SecurityUtils.getSubject().getPrincipal();
//
//        //查询用户id所对应的权限或者从数据库中动态查询权限
//        List<String> perms = menuService.findPersonMenuByid(person.getPid());

        //进行权限对比
//        info.addStringPermissions(perms);


        return info;
    }


    //认证(登录)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {



        //强转 authenticationToken是UsernamePasswordToken的大类
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //从数据库查询账号
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("nickname",token.getUsername());
        List<User> list = userService.list(wrapper);


        //这里只验证账号存不存
        if (list.size() < 1) {
            return null;
        }
        User user = list.get(0);
        //审核
        //需要自定义异常类 继承 AuthenticationException (从Controller抛异常哪里去) 重写带shoir的方法
//        if (user.getStatus() !=0 ){
//
//            throw new LoginException("账号异常");
//        }
        // 登录成功后返回前台
        //固定方法 参数分别是:用户 密码 盐 登录成功后名称
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),user.getNickname());
    }
}
